package com.example.li_han.dao;

import com.example.li_han.pojo.User;
import com.example.li_han.utils.ConnUtils;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    /**
     * 添加用户（注册）
     */
    public int addUser(User user) {
        int flag = 0;
        Connection conn = null;
        PreparedStatement pst = null;

        String sql = "INSERT INTO user(zhangHao, password, avatar) VALUES(?, ?, ?)";

        try {
            conn = ConnUtils.getConn();
            pst = conn.prepareStatement(sql);
            pst.setString(1, user.getZhangHao());
            pst.setString(2, user.getPassword());
            pst.setString(3, user.getAvatar());
            flag = pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("添加用户失败", e);
        } finally {
            closeResources(null, pst, conn);
        }
        return flag;
    }

    /**
     * 删除用户
     */
    public int deleteUser(int userId) {
        int flag = 0;
        Connection conn = null;
        PreparedStatement pst = null;

        String sql = "DELETE FROM user WHERE userId = ?";

        try {
            conn = ConnUtils.getConn();
            pst = conn.prepareStatement(sql);
            pst.setInt(1, userId);
            flag = pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("删除用户失败", e);
        } finally {
            closeResources(null, pst, conn);
        }
        return flag;
    }

    /**
     * 修改用户信息
     */
    public int updateUser(User user) {
        int flag = 0;
        Connection conn = null;
        PreparedStatement pst = null;

        String sql = "UPDATE user SET zhangHao = ?, password = ?, avatar = ? WHERE userId = ?";

        try {
            conn = ConnUtils.getConn();
            pst = conn.prepareStatement(sql);
            pst.setString(1, user.getZhangHao());
            pst.setString(2, user.getPassword());
            pst.setString(3, user.getAvatar());
            pst.setInt(4, user.getUserId());
            flag = pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("修改用户失败", e);
        } finally {
            closeResources(null, pst, conn);
        }
        return flag;
    }

    /**
     * 根据ID查询用户
     */
    public User getUserById(int userId) {
        User user = null;
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        String sql = "SELECT * FROM user WHERE userId = ?";

        try {
            conn = ConnUtils.getConn();
            pst = conn.prepareStatement(sql);
            pst.setInt(1, userId);
            rs = pst.executeQuery();

            if (rs.next()) {
                user = new User(
                        rs.getInt("userId"),
                        rs.getString("zhangHao"),
                        rs.getString("password"),
                        rs.getString("avatar"),
                        rs.getString("registerTime")
                );
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询用户失败", e);
        } finally {
            closeResources(rs, pst, conn);
        }
        return user;
    }

    /**
     * 根据账号密码查询用户（登录验证）
     */
    public User getUserByLogin(String zhangHao, String password) {
        User user = null;
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        String sql = "SELECT * FROM user WHERE zhangHao = ? AND password = ?";

        try {
            conn = ConnUtils.getConn();
            pst = conn.prepareStatement(sql);
            pst.setString(1, zhangHao);
            pst.setString(2, password);
            rs = pst.executeQuery();

            if (rs.next()) {
                user = new User(
                        rs.getInt("userId"),
                        rs.getString("zhangHao"),
                        rs.getString("password"),
                        rs.getString("avatar"),
                        rs.getString("registerTime")
                );
            }
        } catch (SQLException e) {
            throw new RuntimeException("登录验证失败", e);
        } finally {
            closeResources(rs, pst, conn);
        }
        return user;
    }

    /**
     * 查询所有用户
     */
    public List<User> getAllUsers() {
        List<User> userList = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        String sql = "SELECT * FROM user";

        try {
            conn = ConnUtils.getConn();
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery();

            while (rs.next()) {
                User user = new User(
                        rs.getInt("userId"),
                        rs.getString("zhangHao"),
                        rs.getString("password"),
                        rs.getString("avatar"),
                        rs.getString("registerTime")
                );
                userList.add(user);
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询所有用户失败", e);
        } finally {
            closeResources(rs, pst, conn);
        }
        return userList;
    }

    /**
     * 根据账号查询用户（用于检查账号是否已存在）
     */
    public User getUserByZhangHao(String zhangHao) {
        User user = null;
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        String sql = "SELECT * FROM user WHERE zhangHao = ?";

        try {
            conn = ConnUtils.getConn();
            pst = conn.prepareStatement(sql);
            pst.setString(1, zhangHao);
            rs = pst.executeQuery();

            if (rs.next()) {
                user = new User(
                        rs.getInt("userId"),
                        rs.getString("zhangHao"),
                        rs.getString("password"),
                        rs.getString("avatar"),
                        rs.getString("registerTime")
                );
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询用户失败", e);
        } finally {
            closeResources(rs, pst, conn);
        }
        return user;
    }

    /**
     * 关闭数据库资源
     */
    private void closeResources(ResultSet rs, PreparedStatement pst, Connection conn) {
        try {
            if (rs != null) rs.close();
            if (pst != null) pst.close();
            if (conn != null) ConnUtils.closeConnection(conn);
        } catch (SQLException e) {
            throw new RuntimeException("关闭数据库资源失败", e);
        }
    }
}